<?php

/**
 * 接口controller
 * 主要是调用第三方接口方法
 * @author wangwx 2015-5-13
 */

namespace mybackend\controllers;

use common\services\myhtsq\ErpInterfaceService;
use common\services\myhtsq\ContractService;
use yii\filters\AccessControl;
use common\support\CacheManage;
use common\entities\myhtsq\ActionCode;

class ErpInterfaceController extends BaseController {

    protected $_erpInterfaceService;

    private  $_contractService;

    /**
     * @param string $id
     * @param \yii\base\Module $module
     * @param \common\services\myhtsq\ErpInterfaceService $erpInterfaceService
     * @param ContractService|ContractService $contractService
     * @param array $config
     */
    public function __construct($id, $module, ErpInterfaceService $erpInterfaceService,
        ContractService $contractService, $config = array()) {
        $this->_erpInterfaceService = $erpInterfaceService;
        $this->_contractService = $contractService;
        parent::__construct($id, $module, $config);
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['verify-token', 'get-contracts-for-erp'],
                        'allow' => true
                    ],
                    [
                        'actions' => ['get-companies', 'get-users', 'get-erp-customer-info','get-account-hk-list','export-refund'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    
    protected function roleAuthRules() {
        return [
            'actions' => ['GetAccountHkList'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'GetAccountHkList' => ActionCode::CONTRACT_THK,
                    ]
                ]
            ]
        ];
    }

    /**
     * 获取 客户信息-合同签署公司（账套公司）
     * @param string $keyword 搜索关键字
     */
    public function actionGetCompanies($keyword = '') {
        $data = $this->_erpInterfaceService->getCompanies($keyword);
        $this->exportJson($data, $this->_erpInterfaceService->getErrCode(), $this->_erpInterfaceService->getErrMsg());
    }

    /**
     * 根据关键字，获取用户列表
     */
    public function actionGetUsers($keyword, $limit) {
        if (empty($keyword)) {//是否传值为空
            $data = [];
        } else {
            $data = $this->_erpInterfaceService->getUsers($keyword, $limit);
        }
        $this->exportJson($data, $this->_erpInterfaceService->getErrCode(), $this->_erpInterfaceService->getErrMsg());
    }

    /**
     * 检验商家系统请求的token是否正确
     */
    public function actionVerifyToken($token='') {
    	if (empty($token)) {
    		$token = $this->getParam('token','post');
    	}
    	
    	if (empty($token)) {
    		$this->exportJson(['result' => false], -1, 'token不能为空');
    	}
    	
    	
    	//token有效性验证
    	if (CacheManage::getERPApiTokenCache($token) == 'verify') {
    		CacheManage::deleteERPApiTokenCache($token);//验证后，删除token缓存
    		$this->exportJson(['result' => true], $this->_erpInterfaceService->getErrCode(), $this->_erpInterfaceService->getErrMsg());
    	}else{
    		$this->exportJson(['result' => false], -1, 'token无效');
    	}
        
    }

    /**
     * 获取商家系统客户信息
     */
    public function actionGetErpCustomerInfo($keyword) {
        if (empty($keyword)) {//是否传值为空
            $data = [];
        } else {
            $data = $this->_erpInterfaceService->postERPCustomerApi($keyword);
        }
        $this->exportJson($data, $this->_erpInterfaceService->getErrCode(), $this->_erpInterfaceService->getErrMsg());
    }

    /**
     * 取财务系统的回款信息
     */
    public function actionGetAccountHkList() {
        $paymentAccountName = $this->getParam('paymentAccountName');
        $data = $this->_erpInterfaceService->getAccountHkList($paymentAccountName);
        $result = null;
        if($data){
            foreach ($data as $k => $val) {
                !empty($val['payment_date']) && $val['payment_date'] = date('Y-m-d',strtotime($val['payment_date']));
                $result[$k] = $val;
            }
        }else{
            $this->exportJson([], '999', '接口异常或查询无数据!');
        }
        $this->exportJson($result, $this->_erpInterfaceService->getErrCode(), $this->_erpInterfaceService->getErrMsg());
    }

    /**
     * erp获取合同数据
     * 调用：/api/index.php?r=/erp-interface/get-contracts-for-erp&propertyId=合同性质ID&reviewDate=审核日期&page=
     */
    public function actionGetContractsForErp(){
        //合同性质ID
        $propertyId = $this->getParam('propertyId');
        //审核日期
        $reviewDate = $this->getParam('reviewDate');
        //当前页码
        $page = $this->getParam('page');
        //分页大小
        $pageSize = $this->getParam('pageSize');

        $data = $this->_contractService->getContractsForERP($propertyId, $reviewDate, $page, $pageSize);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionExportRefund(){

        ini_set('max_execution_time', 180);
        ini_set('memory_limit', -1);
        set_time_limit(0);
        $paymentAccountName = $this->getParam('paymentAccountName');
        $data = $this->_erpInterfaceService->exportAccountHkList($paymentAccountName);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }
}
